package com.web.web.filter;


import com.web.farme.redis.RedisCache;
import com.web.web.request.RedisSessionHttpServletRequest;
import com.web.web.session.RedisSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 现在过滤器中拦截所有的request请求 在转换成自己的 redisSessionRequest 请求 并拿到Session
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RedisSessionFilter implements Filter {

    private FilterConfig filterConfig;

    private final RedisCache redisCache;

    @Override
    public void init(FilterConfig filterConfig) {
       this.filterConfig = filterConfig;
       log.info(this.getClass().getName() + "filter initialization.");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        RedisSessionHttpServletRequest redisSessionHttpServletRequest = new RedisSessionHttpServletRequest(httpServletRequest, httpServletResponse, this.redisCache, this.filterConfig.getServletContext());
        HttpSession session = redisSessionHttpServletRequest.getSession();
        //将请求转发给过滤器链下一个filter , 如果没有filter那就是你请求的资源
        filterChain.doFilter(redisSessionHttpServletRequest, httpServletResponse);
        if (session instanceof RedisSession) {
            ((RedisSession) session).updateExpire();
        }
    }

    @Override
    public void destroy() {
        log.info(this.getClass().getName() + " filter destroy.");
    }
}
